<?php
/**
 * Created by PhpStorm.
 * User: zhangligang
 * Date: 2018/7/22
 * Time: 上午10:25
 */

namespace App\Http\Controllers;


use App\Models\Contract;
use App\Models\Teacher;
use App\Models\User;
use App\Providers\MyJwt;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cookie;
use Illuminate\Support\Facades\Redis;

class DefaultController extends Controller
{
    private $attribute;

    private $number;

    public function __construct(Request $request)
    {
        parent::__construct();
        if (!$this->number || !in_array($this->number, [85001, 85002, 85003, 85004, 85005])) {
            $this->number = Redis::get(Cookie::get('PHPSESSID'));
            if (!$this->number || !in_array($this->number, [85001, 85002, 85003, 85004, 85005])) {
                $this->number = $request->get('number');
                if ($this->number && in_array($this->number, [85001, 85002, 85003, 85004, 85005])) {
                    Redis::setex(Cookie::get('PHPSESSID'), 3600, $this->number);
                }
            }
        }
        if (!$this->number || !in_array($this->number, [85001, 85002, 85003, 85004, 85005])) {
            session_start();
            \phpCAS::setDebug('./cas.log');
            \phpCAS::client(CAS_VERSION_2_0,'authserver.hznu.edu.cn',443,'/authserver',true);
            \phpCAS::setNoCasServerValidation();
            \phpCAS::handleLogoutRequests();
            \phpCAS::forceAuthentication();
            $this->attribute = \phpCAS::getAttributes();
        }

    }

    public function index(Request $request)
    {
        if (!$this->number) {
            $ticket = $request->cookies->get('PHPSESSID');
            $number = $this->getNumber();
        } else {
            $ticket = $this->madeTicket($this->number);
            $number = $this->number;
        }
        if ($number) {
//            if ($number == 'te01') {
//                $number = 553687;
//            }
            $user = User::where('number', $number)->first();
            if (!$user) {
                $user = new User();
                $user->number = $number;
                $user->realname = $this->getRealname();
                $user->role = 1;
                $user->created_at = date('Y-m-d H:i:s', time());
                $user->updated_at = date('Y-m-d H:i:s', time());
                $user->save();
            }
            $contract = Contract::where('user_id', $user->id)->where('status', 1)->orderBy('id', 'desc')->first();
            if ($contract && strtotime($contract->end_at) < time()) {
                if (strtotime($contract->end_at) - strtotime($contract->start_at) > 3600*24*365*5) {
                    return view('default.index');
                }
            }
            $timeout = (int)((time()+7200)/3600)*3600;
            $jwt = new MyJwt();
            $jwt->payload['uid'] = $user->id;
            $jwt->payload['role'] = $user->role;
            $jwt->payload['timeout'] = $timeout;
            $jwt->payload['ticket'] = $ticket;
            $cacheKey = sprintf('ht:login:uid:%d', $user->id);
            Redis::setex($cacheKey, 7260, $timeout);
            $token = $jwt->encode($jwt->payload, MyJwt::ENCODE_KEY, $jwt->header['alg']);
            switch ($user->role) {
                case 1 : return $this->teacherAction($user, $token);
                case 2 : return $this->hroAction($user, $token);
                case 3 : return $this->financeAction($user, $token);
                case 4 : return $this->assetAction($user, $token);
                case 5 : return $this->managerAction($user, $token);
            }
        }
        return view('default.index');
    }

    public function logout(Request $request)
    {
        $token = $request->get('_token');
        $jwt = new MyJwt();
        $jwtCode = $jwt->decode($token, MyJwt::ENCODE_KEY);
        Redis::setex(sprintf('ht:login:uid:%d', $jwtCode['uid']), 1, null);
        if (!Redis::get(Cookie::get('PHPSESSID'))) {
            \phpCAS::logout(['service' => 'https://authserver.hznu.edu.cn/authserver/logout?ticket='.$jwtCode['ticket']]);
            redirect('https://authserver.hznu.edu.cn/authserver/logout?ticket='.$jwtCode['ticket']);
        } else {
            Redis::setex(Cookie::get('PHPSESSID'), 1, null);
            redirect($this->domain);
        }
        return $this->baseView($request, 'default.logout', ['ticket' => $jwtCode['ticket']]);
    }

    public function contractTemplate(Request $request, $contractId)
    {
        return $this->baseView($request, 'default.template.view', ['contractId' => $contractId]);
    }

    private function teacherAction(User $user, $token)
    {
        $teacher = Teacher::where('user_id', $user->id)->first();
        if (!$teacher) {
            $teacher = new Teacher();
            $teacher->user_id = $user->id;
            $teacher->status = 0;
            $teacher->created_at = date('Y-m-d H:i:s', time());
            $teacher->updated_at = date('Y-m-d H:i:s', time());
            $teacher->save();
        }
        return redirect('/teacher/file.html?_token='.$token.'&role'.$user->role);
    }

    private function hroAction(User $user, $token)
    {
        return redirect('/hro/teacher.html?_token='.$token.'&role='.$user->role);
    }

    private function financeAction(User $user, $token)
    {
        return redirect('/finance/rent.html?_token='.$token.'&role='.$user->role);
    }

    private function assetAction(User $user, $token)
    {
        return redirect('/asset/repair.html?_token='.$token.'&role='.$user->role);
    }

    private function managerAction(User $user, $token)
    {
        return redirect('/manager/apart.html?_token='.$token.'&role='.$user->role);
    }

    public function contractIdentity(Request $request, $contractId)
    {
        return $this->baseView($request, 'default.contract.identity', ['contractId' => $contractId]);
    }

    private function getNumber()
    {
        return $this->attribute['uid'];
    }

    private function getRealname()
    {
        return $this->attribute['userName'];
    }

    private function madeTicket()
    {
        return md5($this->number);
    }
}